/**
 * Copyright 2012 BTChip 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.btchip.protocol;

import java.io.IOException;
import java.util.Vector;

import com.codeminders.hidapi.ClassPathLibraryLoader;
import com.codeminders.hidapi.HIDDevice;
import com.codeminders.hidapi.HIDDeviceInfo;
import com.codeminders.hidapi.HIDManager;

public class BTChipEnumerator {
	
	private static final int BTCHIP_VENDOR_ID = 0x2581;
	private static final int BTCHIP_PRODUCT_ID = 0x1807;
	private static final int BTCHIP_APP_INTERFACE = 1;
	private static final int BTCHIP_APP_USAGE_PAGE = 65440;
	
	static {
		ClassPathLibraryLoader.loadNativeHIDLibrary();
	}	
	
	private HIDManager manager;

	
	public BTChipEnumerator() throws IOException {
		manager = HIDManager.getInstance();
	}

	public String[] listDevices() throws BTChipCommunicationException {
		try {
			Vector<String> result = new Vector<String>();
			HIDDeviceInfo[] devices = manager.listDevices();
			if (devices != null) {
				for (HIDDeviceInfo device : devices) {
					if ((device.getVendor_id() == BTCHIP_VENDOR_ID) &&
							(device.getProduct_id() == BTCHIP_PRODUCT_ID) &&
							((device.getInterface_number() == BTCHIP_APP_INTERFACE) ||
							 (device.getUsage_page() == BTCHIP_APP_USAGE_PAGE))) {
						result.add(device.getPath());
					}
				}
			}
			return result.toArray(new String[0]);
		}
		catch(IOException e) {
			throw new BTChipCommunicationException(e);
		}
	}

	public BTChip getDevice(String name)
			throws BTChipCommunicationException {
		try {
			HIDDevice device = manager.openByPath(name);
			return new BTChip(device);
		}
		catch(Exception e) {
			throw new BTChipCommunicationException(e);
		}		
	}	
	
	public void release() {
		manager.release();
	}
	
}
